package com.ynet.middleground.approve.listener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.constant.VotingVariables;
import com.ynet.middleground.approve.constant.WorkflowConstants;
import com.ynet.middleground.approve.model.UserCenterModel;

/**
 * @author liulx
 * @description 设置会签人员列表监听器
 * @date 2019-12-24 19:27
 */
@Component
@DependsOn("springContextUtils")
public class SetVotingUserListener extends BaseListener implements TaskListener, VotingVariables {

    private RuntimeService runtimeService = SpringContextUtils.getBean(RuntimeService.class);
    private UserCenterModel userCenterModel = SpringContextUtils.getBean(UserCenterModel.class);

    /**
     * 绘制流程图中，指定的会签人员字段，需要和流程图中字段名称保持一致
     */
    private FixedValue assigneeListValue;

    /**
     * 绘制流程图中，指定的会签人员所在组字段，需要和流程图中字段名称保持一致
     */
    private FixedValue assigneeListGroupValue;

    @Override
    public void notify(DelegateTask delegateTask) {
        if (assigneeListValue != null) {
            // 获取配置的会签人员列表
            String listValue = assigneeListValue.getExpressionText();
            if (StringUtils.isNotBlank(listValue)) {
                List<String> assigneeList = Arrays.stream(listValue.split(",")).collect(Collectors.toList());
                if (assigneeList.isEmpty()) {
                    throw new BusinessException("会签人员列表不能为空", "ECAP0412");
                }
                // 获取流程id
                String exId = delegateTask.getExecutionId();
                runtimeService.setVariable(exId, ASSIGNEE_LIST, assigneeList);
            }
        }

        if (assigneeListGroupValue != null) {
            // 获取配置的会签人员所在组列表
            String listValue = assigneeListGroupValue.getExpressionText();
            if (StringUtils.isNotBlank(listValue)) {
                List<String> assigneeGroupList = Arrays.stream(listValue.split(",")).collect(Collectors.toList());
                // 获取流程id
                String exId = delegateTask.getExecutionId();
                List<Integer> assigneeList = getAssigneeList(assigneeGroupList, delegateTask);
                if (assigneeList.isEmpty()) {
                    throw new BusinessException("会签人员列表不能为空", "ECAP0412");
                }
                runtimeService.setVariable(exId, ASSIGNEE_LIST, assigneeList);
            }
        }
    }

    /**
     * 获取用户列表
     * 
     * @param assigneeGroupList
     *            用户组列表
     * @param delegateTask
     *            执行任务
     * @return 用户列表
     */
    private List<Integer> getAssigneeList(List<String> assigneeGroupList, DelegateTask delegateTask) {
        String channel = getChannel(delegateTask);
        String operationUserId = getOperationUserId(delegateTask);
        List<Integer> userIds = new ArrayList<>();
        // 收集用户id
        assigneeGroupList.stream().forEach(group -> {
            String[] groupValue =
                group.replace(WorkflowConstants.CANDIDATE_GROUP_DEPARTMENT_ROLE_PREFIX, "").split("-");
            List<Integer> idList = userCenterModel.listUserRelationByGroupId(groupValue[0], groupValue[1], channel,
                Integer.valueOf(operationUserId));
            userIds.addAll(idList);
        });
        return userIds.stream().distinct().collect(Collectors.toList());
    }

}
